<?php
// +----------------------------------------------------------------------
// | 双擎基础框架 [ 基于ThinkLibrary扩展 ]
// +----------------------------------------------------------------------
// | 感谢ThinkLibrary原作者Anyon的封装
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2024 https://www.sqm.la All rights reserved.
// +----------------------------------------------------------------------
// | Author: rotoos <87291030@qq.com>
// +----------------------------------------------------------------------
namespace think\admin\service;

use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Dm\Dm;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use think\admin\Exception;
use think\admin\model\SysEmail;
use think\admin\Service;

/**
 * 阿里云邮件发送服务
 * @class AlibabaEmailService
 * @package think\admin\service
 */
class AlibabaEmailService extends Service
{
    /**
     * AccessKey ID
     * @var string
     */
    protected string $accessKeyId;

    /**
     * accessKey Secret
     * @var string
     */
    protected string $accessKeySecret;

    /**
     * Region Id
     * @var string
     */
    protected string $regionId;

    /**
     * 发送单个邮件
     * @param $to
     * @param string $sendAccount
     * @param string $sendUser
     * @param string $subject
     * @param string $content
     * @return bool
     */
    public function singleSendMail($to, string $sendAccount = '', string $sendUser = '', string $subject = '', string $content = ''): bool
    {
        try {
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId($this->regionId)
                ->asDefaultClient();

            $result = Dm::v20151123()
                ->singleSendMail()
                ->withAccountName($sendAccount)
                ->withFromAlias($sendUser)
                ->withAddressType(1)
                ->withReplyToAddress("false")
                ->withToAddress($to)
                ->withHtmlBody($content)
                ->withTextBody($content)
                ->withSubject($subject)
                ->request();

            $state = false;
            $dat = [
                'engine' => 'ALIYUN',
                'send_account' => $sendAccount,
                'send_user' => $sendUser,
                'receive_accounts' => $to,
                'subject' => $subject,
                'content' => $content
            ];
            if ($result->toArray()) {
                $state = true;
                $dat['receipt_info'] = json_encode($result->toArray());
            }
            SysEmail::mk()->insert($dat);
            return $state;
        } catch (ClientException|ServerException $e) {
            return false;
        }
    }

    /**
     * 批量发送模板邮件
     * @param array $to
     * @param string $sendAccount
     * @param string $tagName
     * @param string $templateName
     * @return bool
     */
    public function batchSendEmail(array $to, string $sendAccount = '', string $tagName = '', string $templateName = ''): bool
    {
        try {
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId($this->regionId)
                ->asDefaultClient();

            $result = Dm::v20151123()
                ->batchSendMail()
                ->withAccountName($sendAccount)
                ->withAddressType(1)
                ->withTagName($tagName)
                ->withTemplateName($templateName)
                ->withReceiversName($to)
                ->request();

            $state = false;
            $dat = [
                'engine' => 'ALIYUN',
                'send_account' => $sendAccount,
                'tag_name' => $tagName,
                'receive_accounts' => implode(',', $to),
                'template_name' => $templateName
            ];
            if ($result->toArray()) {
                $state = true;
                $dat['receipt_info'] = json_encode($result->toArray());
            }
            SysEmail::mk()->insert($dat);
            return $state;
        } catch (ClientException|ServerException $e) {
            return false;
        }
    }

    /**
     * 控制器初始化
     * @return void
     * @throws Exception
     */
    protected function initialize()
    {
        $this->accessKeyId = sysconfig('EMAIL_ALIYUN', 'SQM_EMAIL_ALIYUN_ACCESS_KEY_ID');
        $this->accessKeySecret = sysconfig('EMAIL_ALIYUN', 'SQM_EMAIL_ALIYUN_ACCESS_KEY_SECRET');
        $this->regionId = sysconfig('EMAIL_ALIYUN', 'SQM_EMAIL_ALIYUN_REGION_ID');
    }
}
